package io.yuanqi.hgtcshop.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import io.yuanqi.hgtcshop.config.RedisService;
import io.yuanqi.hgtcshop.entity.dos.GoodsSku;
import io.yuanqi.hgtcshop.entity.dto.TradeDTO;
import io.yuanqi.hgtcshop.entity.enums.CartTypeEnum;
import io.yuanqi.hgtcshop.entity.enums.ResultCode;
import io.yuanqi.hgtcshop.entity.vo.ResultMessage;
import io.yuanqi.hgtcshop.entity.vo.TradeParams;
import io.yuanqi.hgtcshop.exception.ServiceException;
import io.yuanqi.hgtcshop.service.CartService;
import io.yuanqi.hgtcshop.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 买家端，购物车接口
 *
 * @author Chopper
 * @since 2020/11/16 10:04 下午
 */
@Slf4j
@RestController
//@Api(tags = "买家端，购物车接口")
@RequestMapping("/buyer/trade/carts")
public class CartController {

    /**
     * 购物车
     */
    @Autowired
    private CartService cartService;


    @Autowired
    private RedisService redisService;


    @PostMapping("/check")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "skuId", value = "产品ID", required = true, dataType = "Long", paramType = "query"),
//            @ApiImplicitParam(name = "num", value = "此产品的购买数量", required = true, dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "cartType", value = "购物车类型，默认加入购物车", paramType = "query")
//    })
    public ResultMessage<Object> check(@NotNull(message = "产品id不能为空") String skuId,
                                       @NotNull(message = "购买数量不能为空") Boolean flag,
                                       String openId) {
        log.info(".check openId:{} skuId:{} flag:{}", openId, skuId, flag);
        String key = "check_" + openId;
        String value = redisService.getValue(key);
        log.info("从redis中获取的value为:{}", value);
        HashMap<String, Boolean> skuIdAndFlagMaps = Maps.newHashMap();
        if (null != value) {
            skuIdAndFlagMaps = JSON.parseObject(value, new TypeReference<HashMap<String, Boolean>>() {
            });
            log.info("转换的集合为:{}", JSON.toJSONString(skuIdAndFlagMaps));
        }
        skuIdAndFlagMaps.put(skuId, flag);
        redisService.setKeyValue(key, JSON.toJSONString(skuIdAndFlagMaps));
        return ResultUtil.success();
    }


    @PostMapping(value = "/getSkuIds")
    public ResultMessage<List<String>> getCheck(String openId) {
        log.info(".getSkuIds 请求参数openId:{}", openId);
        String key = "check_" + openId;
        List<String> skuIds = Lists.newArrayList();
        String value = redisService.getValue(key);
        HashMap<String, Boolean> skuIdAndFlagMaps = Maps.newHashMap();
        if (null != value) {
            skuIdAndFlagMaps = JSON.parseObject(value, new TypeReference<HashMap<String, Boolean>>() {
            });

            for (Map.Entry<String, Boolean> entry : skuIdAndFlagMaps.entrySet()) {
                String skuId = entry.getKey();
                Boolean value1 = entry.getValue();
                if (value1) {
                    skuIds.add(skuId);
                }
            }
        }
        log.info(".getCheck 返回结果为:{}", JSON.toJSONString(skuIds));
        return ResultUtil.data(skuIds);
    }

    @PostMapping(value = "/destroy")
    public ResultMessage<Boolean> destroy(String openId) {
        String key = "check_" + openId;
        redisService.deleteKey(key);
        return ResultUtil.success();
    }


    //   //  @ApiOperation(value = "向购物车中添加一个产品")
    @PostMapping
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "skuId", value = "产品ID", required = true, dataType = "Long", paramType = "query"),
//            @ApiImplicitParam(name = "num", value = "此产品的购买数量", required = true, dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "cartType", value = "购物车类型，默认加入购物车", paramType = "query")
//    })
    public ResultMessage<Object> add(@NotNull(message = "产品id不能为空") String skuId,
                                     @NotNull(message = "购买数量不能为空") @Min(value = 1, message = "加入购物车数量必须大于0") Integer num,
                                     String openId) {
        try {
            log.info(".add skuId:{} num:{} openId:{}", skuId, num, openId);
            //读取选中的列表
            cartService.add(skuId, num, openId, false);
            return ResultUtil.success();
        } catch (ServiceException se) {
            log.error(se.getMsg(), se);
            throw se;
        } catch (Exception e) {
            log.error(ResultCode.CART_ERROR.message(), e);
            throw new ServiceException(ResultCode.CART_ERROR);
        }
    }


    //  @ApiOperation(value = "获取购物车页面购物车详情")
    @GetMapping("/all")
    public ResultMessage<List<GoodsSku>> cartAll(String openId) {
        log.info(".cartAll openId:{}", openId);
        return ResultUtil.data(this.cartService.cartAll(openId));
    }

    //  @ApiOperation(value = "获取购物车数量")
    @GetMapping("/count")
    public ResultMessage<Long> cartCount(@RequestParam(required = false) Boolean checked) {
        return ResultUtil.data(this.cartService.getCartNum(checked));
    }


    //  @ApiOperation(value = "清空购物车")
    @DeleteMapping()
    public ResultMessage<Object> clean(String openId) {
        log.info(".cartAll openId:{}", openId);
        cartService.clean(openId);
        return ResultUtil.success();
    }


    //   //  @ApiOperation(value = "删除购物车中的一个或多个产品")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "skuIds", value = "产品id", required = true, dataType = "Long", paramType = "path", allowMultiple = true)
//    })
    @DeleteMapping(value = "/sku/remove")
    public ResultMessage<Object> delete(String[] skuIds, String openId) {
        cartService.delete(skuIds, openId);
        return ResultUtil.success();
    }


    //  @ApiOperation(value = "获取结算页面购物车详情")

    @GetMapping("/checked")
    public ResultMessage<TradeDTO> cartChecked(@NotNull(message = "读取选中列表") String way) {
        try {
            //读取选中的列表
            return ResultUtil.data(this.cartService.getCheckedTradeDTO(CartTypeEnum.valueOf(way)));
        } catch (ServiceException se) {
            log.error(se.getMsg(), se);
            throw se;
        } catch (Exception e) {
            log.error(ResultCode.CART_ERROR.message(), e);
            throw new ServiceException(ResultCode.CART_ERROR);
        }
    }

    //   //  @ApiOperation(value = "选择收货地址")
    @GetMapping("/shippingAddress")
    public ResultMessage<Object> shippingAddress(@NotNull(message = "收货地址ID不能为空") String shippingAddressId,
                                                 String way) {
        try {
            cartService.shippingAddress(shippingAddressId, way);
            return ResultUtil.success();
        } catch (ServiceException se) {
            log.error(ResultCode.SHIPPING_NOT_APPLY.message(), se);
            throw new ServiceException(ResultCode.SHIPPING_NOT_APPLY);
        } catch (Exception e) {
            log.error(ResultCode.CART_ERROR.message(), e);
            throw new ServiceException(ResultCode.CART_ERROR);
        }
    }


    //   //  @ApiOperation(value = "创建交易")
    @PostMapping(value = "/create/trade", consumes = "application/json", produces = "application/json")
    public ResultMessage<Object> crateTrade(String openId, String[] skuIds, String addressId, BigDecimal totalPrice) {
        try {
            //读取选中的列表
            return ResultUtil.data(this.cartService.createTrade(openId, skuIds, addressId, totalPrice));
        } catch (ServiceException se) {
            log.info(se.getMsg(), se);
            throw se;
        } catch (Exception e) {
            log.error(ResultCode.ORDER_ERROR.message(), e);
            throw e;
        }
    }
}
